/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dal;

import entity.Book;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author haohao
 */
public class DBConnection {

    public Connection getConnection() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            return DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=ViewBook", "sa", "fat123456");
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public List<Book> getAll() {
        try {
            List<Book> list = new ArrayList<Book>();
            Connection con = new DBConnection().getConnection();
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from Book  ");
            Book p;
            while (rs.next()) {
                p = new Book();
                p.setId(rs.getInt(1));
                p.setName(rs.getString(2));
                p.setAuthor(rs.getString(3));
                p.setPublisher(rs.getString(4));
                p.setYear(rs.getInt(5));
                p.setDescription(rs.getString(6));
                list.add(p);
            }
            return list;
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}
